package com.gz.purchase.app;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.purchase.R;
import com.gz.purchase.adapter.InStorageAdapter;
import com.gz.purchase.adapter.OutStorageCartAdapter;
import com.gz.purchase.adapter.SpinnerAdapter;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IProduct;
import com.gz.purchase.library.listener.GetInStorageShopsListener;
import com.gz.purchase.library.listener.InStorageConfirmListener;
import com.gz.purchase.library.listener.SerarchProductListener;
import com.gz.purchase.library.pojo.CustomerSpinnerObject;
import com.gz.purchase.library.pojo.ShopInfo;
import com.gz.purchase.library.pojo.StorageCheckProductInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.CrashHandler;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.library.util.Tools;
import com.gz.purchase.util.ToastUtils;
import com.gz.purchase.widget.InStoragePopWindow;
import com.gz.purchase.widget.LoadingCover;
import com.gz.purchase.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.Base64;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 入库界面
 */
public class InStorageActivity extends BaseActivity implements View.OnClickListener,
         SpinerPopWindow.ISpinnerOnItemSelectListener, RadioGroup.OnCheckedChangeListener {
    private String TAG  = InStorageActivity.class.getSimpleName();
    private ImageView iv_actionbar_up;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;

    private EditText et_search_content;
    private ImageView iv_search_trigger;
    private ImageView iv_search_delete;//搜索框中的删除

    private TextView tv_choice_shop; //商店选择
    private TextView tv_order; // 排序
    private TextView tv_in_StorageCart;// 入库操作

    private Dialog mMenudialog;// 点击出库操作弹出对话框
    private View mMenudialogLayout;// dialog 的自定义布局
    private RadioGroup rg_in_choices; // 入库方式 RadioGroup
    private EditText et_notes; // dialog 里的备注编辑框
    private Button bt_in_storage; // dialog 里的取消按钮
    private Button bt_cancle; // dialog 里的确定按钮
    private String THE_WAY_INFO = Define.RADIO_BUTTOM_CGRK; // 存放入库方式

    private PullToRefreshListView mPullListView;
    private Dialog mLoadingData;
    private UserInfo info ;

    // 库房下拉相关变量
    private List<CustomerSpinnerObject> storageroomList ;
    private SpinnerAdapter partSpinnerAdapter;
    private SpinerPopWindow mPartSpinnerPopWindow;

    // 商品列表相关
    private InStorageAdapter mAdapter;
    private List<StorageCheckProductInfo> mDataList;

    private MyGetInStorageShopsListener myGetInStorageShopsListener;
    private MySerarchProductListener mySerarchProductListener;
    private MyInStorageConfirmListener myInStorageConfirmListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_storage);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_activity_head_layout);//自定义ActionBar布局
        initView();
        initListener();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mySerarchProductListener.release();
        myGetInStorageShopsListener.release();
        myInStorageConfirmListener.release();
    }

    private void initView() {
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        iv_actionbar_up = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        et_search_content = (EditText) this.findViewById(R.id.et_search_content);
        iv_search_delete = (ImageView) this.findViewById(R.id.iv_search_delete);
        iv_search_trigger = (ImageView) this.findViewById(R.id.iv_search_trigger);

        tv_choice_shop = (TextView) this.findViewById(R.id.tv_choice_shop);
        tv_order = (TextView) this.findViewById(R.id.tv_order);
        tv_in_StorageCart = (TextView) this.findViewById(R.id.tv_in_StorageCart);

        mPullListView = (PullToRefreshListView) this.findViewById(R.id.list);
        mPullListView.setMode(PullToRefreshBase.Mode.DISABLED);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

        // 点击入库操作后弹出的dialog窗口
        mMenudialog = new Dialog(this, R.style.DialogTheme);
        mMenudialogLayout = LayoutInflater.from(getApplicationContext()).inflate(R.layout.popwindow_layout, null);
        rg_in_choices = (RadioGroup) mMenudialogLayout.findViewById(R.id.rg_in_choices);
        et_notes = (EditText) mMenudialogLayout.findViewById(R.id.et_notes);
        bt_in_storage = (Button) mMenudialogLayout.findViewById(R.id.bt_in_storage);
        bt_cancle = (Button) mMenudialogLayout.findViewById(R.id.bt_cancle);

        mMenudialog.setContentView(mMenudialogLayout);
        mMenudialog.setCancelable(false);
        mMenudialog.setCanceledOnTouchOutside(false);

    }

    private void initListener(){

        iv_actionbar_up.setOnClickListener(this);

        iv_search_trigger.setOnClickListener(this);//搜索
        iv_search_delete.setOnClickListener(this);//删除

        tv_in_StorageCart.setOnClickListener(this);// 入库操作
        tv_choice_shop.setOnClickListener(this);// 商家选择

        bt_in_storage.setOnClickListener(this);
        bt_cancle.setOnClickListener(this);
        rg_in_choices.setOnCheckedChangeListener(this);

        mySerarchProductListener = new MySerarchProductListener(this);
        myGetInStorageShopsListener = new MyGetInStorageShopsListener(this);
        myInStorageConfirmListener = new MyInStorageConfirmListener(this);

    }

    private void initData(){
        tv_actionbar_title.setText("入库");
        if (info != null){
            tv_actionbar_deliveryName.setText(info.getName() + "：" + info.getUser_name());
        }

        mDataList = new ArrayList<StorageCheckProductInfo>();
        mAdapter = new InStorageAdapter(this,mDataList);
        mPullListView.setAdapter(mAdapter);

        storageroomList = new ArrayList<CustomerSpinnerObject>();
        partSpinnerAdapter = new SpinnerAdapter(this,storageroomList);
        mPartSpinnerPopWindow = new SpinerPopWindow(this);
        mPartSpinnerPopWindow.setAdatper(partSpinnerAdapter);
        mPartSpinnerPopWindow.setItemListener(this);

        et_search_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(et_search_content.getText().toString())) {
                    iv_search_delete.setVisibility(View.GONE);
                } else {
                    iv_search_delete.setVisibility(View.VISIBLE);
                }


            }
        });
        //监听键盘上的enter键
        et_search_content.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_ENTER) {
                    String content = et_search_content.getText().toString();
                    if (!TextUtils.isEmpty(content)) {
                        mLoadingData.show();
                        // 把所有商家置为未选中状态
                        resetStorageRoomState();
                        String product_name = et_search_content.getText().toString();
                        IProduct.getInstance().getSearchProducts(product_name,-1,mySerarchProductListener);
                    }
                    return true;
                }
                return false;
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_choice_shop: // 商家选择
                if (storageroomList.size() == 0){
                    mLoadingData.show();
                    IProduct.getInstance().getShops(myGetInStorageShopsListener);
                }else{
                    mPartSpinnerPopWindow.setWidth(tv_choice_shop.getWidth()*2);
                    mPartSpinnerPopWindow.showAsDropDown(tv_choice_shop);
                }
                break;

            case R.id.iv_search_trigger: // 点击搜索
                String product_name = et_search_content.getText().toString();
                if (TextUtils.isEmpty(product_name)){
                    ToastUtils.showToast(this,"请输入商品名称");
                    return ;
                }
                mLoadingData.show();
                resetStorageRoomState();
                IProduct.getInstance().getSearchProducts(product_name, -1, mySerarchProductListener);
                break;

            case R.id.iv_search_delete: // 搜索框中删除按钮
                et_search_content.setText("");
                break;

            case R.id.iv_actionbar_up: // 返回
                finish();
                break;

            case R.id.tv_in_StorageCart: // 入库操作
                Boolean isEmpty = true; // 记录当前数组里是否有item被选中
                Boolean isDataError = false; //被选中的商品填写的数量是否正确
                for (int i = 0 ; i < mDataList.size() ; i++){
                    if (mDataList.get(i).isSelected()){
                        isEmpty = false;
                        if (mDataList.get(i).getSelectNum() <= 0){
                            isDataError = true;
                            break;
                        }
                    }
                }
                if (isEmpty){ // 没有勾选商品

                    ToastUtils.showToast(this,"请选择商品");
                }else if (isDataError){
                    ToastUtils.showToast(this,"请正确填写商品数量");
                } else{ // 否则

                    mMenudialog.show();
                }
                break;

            case R.id.bt_cancle: // Dialog 里的取消按钮
                mMenudialog.dismiss();
                break;

            case R.id.bt_in_storage:  // Dialog 里的确认入库
                mMenudialog.dismiss();
                confirmInstorage();
                break;
        }

    }

     // 商家下拉列表的点击事件
    @Override
    public void onSpinnerItemClick(int position) {
        mLoadingData.show();
        for(int i = 0 ;i < storageroomList.size() ; i++){
            if (i == position){
                storageroomList.get(i).setIsSelected(true);
            }else{
                storageroomList.get(i).setIsSelected(false);
            }
        }
        ShopInfo info = (ShopInfo) storageroomList.get(position);
        et_search_content.setText("");
        IProduct.getInstance().getSearchProducts(null, info.getShop_id(), mySerarchProductListener);

    }

    // RadioGroup 按钮点击的切换事件
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i){
            case R.id.rb_cgrk:
                THE_WAY_INFO = Define.RADIO_BUTTOM_CGRK;
                break;
            case R.id.rb_pyrk:
                THE_WAY_INFO = Define.RADIO_BUTTOM_PYRK;
                break;
            case R.id.rb_thrk:
                THE_WAY_INFO = Define.RADIO_BUTTOM_THRK;
                break;
        }

    }

    /**
     * 把所有商家置为未选中状态
     */
    private void resetStorageRoomState() {
        if (storageroomList.size()>0){
            for (int i = 0 ; i < storageroomList.size() ; i++){
                storageroomList.get(i).setIsSelected(false);
            }
        }
    }

    /**
     * 移除mDataList里已经选中的商品（入库成功后执行该操作）
     */
    private void removeSelectedItem(){
        Iterator<StorageCheckProductInfo> iterator = mDataList.iterator();
        while (iterator.hasNext()){
            if (iterator.next().isSelected()){
                iterator.remove();
            }
        }
    }
    /**
     * 点击dialog里的入库按钮
     */
    private void confirmInstorage(){
        mLoadingData.show();
        String notes = et_notes.getText().toString();
        JSONArray array = new JSONArray();
        JSONObject object ;
        StorageCheckProductInfo info ;

        try {
            for (int i = 0 ; i < mDataList.size() ; i++){
                if (mDataList.get(i).isSelected()){
                    info = mDataList.get(i);
                    object = new JSONObject();
                    object.put("product_id",info.getProduct_id());
                    object.put("product_num",info.getSelectNum());
                    array.put(object);
                }
            }
        } catch (JSONException e) {
            array = null;
            e.printStackTrace();
        }

        if (array == null){
            mLoadingData.dismiss();
            ToastUtils.showToast(this, "商品入库失败");
        }else if (array.length() == 0){

            mLoadingData.dismiss();
            ToastUtils.showToast(this,"请选择商品");

        } else{
            CrashHandler.i(TAG,array.toString());
            IProduct.getInstance().inStorage(THE_WAY_INFO,notes ,Tools.Base64Encode(array.toString()),myInStorageConfirmListener);
        }


    }
    /**
     * 获取商家列表监听器
     */
    private static class MyGetInStorageShopsListener extends GetInStorageShopsListener {
        private InStorageActivity mOuter;

        public MyGetInStorageShopsListener(InStorageActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<InStorageActivity>(mOuter);
        }

        @Override
        public void onNoShopInfo(String msg) {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, msg);

        }

        @Override
        public void onResponseSuccess(List<ShopInfo> list) {
            if (list == null){
               list = new ArrayList<ShopInfo>();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.storageroomList.clear();
            mOuter.storageroomList.addAll(list);
            mOuter.mPartSpinnerPopWindow.setWidth(mOuter.tv_choice_shop.getWidth()*2);
            mOuter.mPartSpinnerPopWindow.showAsDropDown(mOuter.tv_choice_shop);

        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);
        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "获取商家列表失败");

        }
    }

    /**
     * 根据查询条件查询对应商品的回调监听器
     */
    private static class MySerarchProductListener extends SerarchProductListener {
        private InStorageActivity mOuter;

        public MySerarchProductListener(InStorageActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<InStorageActivity>(mOuter);
        }

        @Override
        public void onSatisfiedProducts() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.mDataList.clear();
            mOuter.mAdapter.notifyDataSetChanged();
            ToastUtils.showToast(mOuter,"无满足条件的商品");

        }

        @Override
        public void onResponseSuccess(List<StorageCheckProductInfo> list) {
            if (list == null){
                onResponseFailed();
                return;
            }
            mOuter.mDataList.clear();
            mOuter.mDataList.addAll(list);
            mOuter.mAdapter.notifyDataSetChanged();
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }

        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }

            ToastUtils.showToast(mOuter,Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }

            ToastUtils.showToast(mOuter,"查询失败");
        }
    }

    /**
     * 入库操作回调监听器
     */
    private static class MyInStorageConfirmListener extends InStorageConfirmListener {
        private InStorageActivity mOuter;

        public MyInStorageConfirmListener(InStorageActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<InStorageActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {

            mOuter.removeSelectedItem();
            mOuter.mAdapter.notifyDataSetChanged();
            mOuter.et_search_content.setText("");
            mOuter.resetStorageRoomState(); // 商家置为未选状态
            mOuter.mLoadingData.dismiss();
        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter,Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter,"商品入库失败");

        }
    }
}
